package com.vm.broadcast;

import java.util.List;

import com.vm.db.OperationDao;
import com.vm.db.UpgradeSoftDao;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Handler;
import android.os.Message;

public class AppInstallReceiver extends BroadcastReceiver {

	public static Handler mainHandler;
	OperationDao operationDao;

	@Override
	public void onReceive(Context context, Intent intent) {
		operationDao = new OperationDao();
		if (intent.getAction().equals(Intent.ACTION_PACKAGE_ADDED)) {
			String packageName = intent.getData().getSchemeSpecificPart();
			PackageManager pm = context.getPackageManager();
			try {
				pm.getApplicationLabel(
						pm.getApplicationInfo(packageName,
								PackageManager.GET_META_DATA)).toString();
			} catch (NameNotFoundException e) {
				e.printStackTrace();
			}
			ActivityManager am = (ActivityManager) context
					.getSystemService(Context.ACTIVITY_SERVICE);
			List<RunningAppProcessInfo> infos = am.getRunningAppProcesses();
			// new File(Environment.getExternalStorageDirectory()
			// .getPath() + "/vmclient/" + name + ".apk");
			for (RunningAppProcessInfo rapi : infos) {
				if (rapi.processName.equals("com.wwtscapp.apk")) {
					if (operationDao.query(packageName) == 1) {
						if (mainHandler != null) {
							Message message = new Message();
							message.what = 100;
							mainHandler.sendMessage(message);
							operationDao.deleteOne(packageName);
							// Toast.makeText(context, name,
							// Toast.LENGTH_LONG).show();
						}
					}
				}
			}

		}
		if (intent.getAction().equals(Intent.ACTION_PACKAGE_REMOVED)) {
			String packageName = intent.getData().getSchemeSpecificPart();
			// Toast.makeText(context, "卸载成功" + packageName, Toast.LENGTH_LONG)
			// // .show();
			// OperationDao operationDao = new OperationDao();
			// int result = operationDao.query(packageName);

			// 从本地数据库中删除该应用
			UpgradeSoftDao dao = new UpgradeSoftDao();
			if (packageName != null) {
				dao.delete(packageName);
			}
			dao.getUpgradeSofts();

			// if (result == 1) {
			// Message message = new Message();
			// message.what = 200;
			// mainHandler.sendMessage(message);
			// }

		}
		if (intent.getAction().equals(Intent.ACTION_PACKAGE_REPLACED)) {
			intent.getData().getSchemeSpecificPart();
		}

	}

}